#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
RagFlow客户端打包脚本
用于将RagFlow客户端打包为可执行文件
支持Mac、Linux和Windows平台
"""

import os
import sys
import shutil
import platform
import subprocess
from pathlib import Path

def run_command(cmd):
    """运行命令并打印输出"""
    print(f"执行命令: {cmd}")
    process = subprocess.Popen(
        cmd, 
        shell=True, 
        stdout=subprocess.PIPE, 
        stderr=subprocess.STDOUT, 
        universal_newlines=True
    )
    
    for line in process.stdout:
        print(line.strip())
    
    process.wait()
    return process.returncode

def clean_build_dirs():
    """清理构建目录"""
    dirs_to_clean = ['build', 'dist']
    for dir_name in dirs_to_clean:
        if os.path.exists(dir_name):
            print(f"清理目录: {dir_name}")
            shutil.rmtree(dir_name)

def install_requirements():
    """安装打包所需的依赖"""
    print("安装打包所需的依赖...")
    run_command("pip install pyinstaller")

def detect_platform():
    """检测当前平台"""
    system = platform.system().lower()
    if system == "darwin":
        return "mac"
    elif system == "linux":
        return "linux"
    elif system == "windows":
        return "windows"
    else:
        print(f"不支持的平台: {system}")
        sys.exit(1)

def build_for_platform(platform_name):
    """为指定平台构建可执行文件"""
    print(f"开始为 {platform_name} 平台构建...")
    
    # 基本的PyInstaller命令
    cmd = "pyinstaller --clean --noconfirm "
    
    # 添加图标（如果存在）
    icon_path = None
    if platform_name == "mac":
        icon_path = "resources/icon.icns"
    elif platform_name == "windows":
        icon_path = "resources/icon.ico"
    
    if icon_path and os.path.exists(icon_path):
        cmd += f"--icon={icon_path} "
    
    # 添加平台特定选项
    if platform_name == "mac":
        cmd += "--windowed "  # macOS上创建.app包
    elif platform_name == "windows":
        cmd += "--windowed "  # Windows上不显示控制台
    
    # 添加数据文件
    cmd += "--add-data resources:resources "
    
    # 如果存在.env文件，也添加到数据文件中
    if os.path.exists(".env"):
        if platform_name == "windows":
            cmd += "--add-data .env;. "
        else:
            cmd += "--add-data .env:. "
    
    # 添加应用程序名称和入口点
    cmd += "--name RagFlow "
    cmd += "ragflow_client/__main__.py"
    
    # 执行构建命令
    return run_command(cmd)

def create_resources_dir():
    """创建资源目录并添加图标文件"""
    if not os.path.exists("resources"):
        os.makedirs("resources")
        print("创建资源目录: resources")
    
    # 这里可以添加代码来生成或复制图标文件

def create_default_config():
    """创建默认配置文件"""
    # 创建默认配置文件
    if not os.path.exists(".env"):
        print("创建默认配置文件: .env")
        with open(".env", "w", encoding="utf-8") as f:
            f.write("# RagFlow 配置文件\n")
            f.write("RAGFLOW_API_URL=\n")
            f.write("RAGFLOW_API_KEY=\n")
            f.write("RAGFLOW_KB_ID=\n")
            f.write("RAGFLOW_KB_NAME=\n")
            f.write("RAGFLOW_PARSER_ID=naive\n")
            f.write("RAGFLOW_DOC_DIR=\n")
            f.write("RAGFLOW_DOC_SUFFIX=md,txt,pdf,docx\n")
            f.write("THEME=light\n")
            f.write("DEBUG=false\n")

def main():
    """主函数"""
    # 清理旧的构建目录
    clean_build_dirs()
    
    # 安装依赖
    install_requirements()
    
    # 创建资源目录
    create_resources_dir()
    
    # 检测当前平台
    current_platform = detect_platform()
    print(f"当前平台: {current_platform}")
    
    # 构建可执行文件
    result = build_for_platform(current_platform)
    
    if result == 0:
        print("\n构建成功!")
        if current_platform == "mac":
            print("可执行文件位于: dist/RagFlow.app")
        elif current_platform == "windows":
            print("可执行文件位于: dist/RagFlow.exe")
        else:
            print("可执行文件位于: dist/RagFlow")
    else:
        print("\n构建失败!")
        sys.exit(1)

if __name__ == "__main__":
    main()